package com.yunbiao.ybbusstopplate.ui.fragment

import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.library_hy_advert.HYAdvertFragment
import com.yunbiao.ybbusstopplate.BuildConfig
import com.yunbiao.ybbusstopplate.R
import com.yunbiao.ybbusstopplate.base.APP
import com.yunbiao.ybbusstopplate.base.BaseActivity
import com.yunbiao.ybbusstopplate.base.BaseFragment
import com.yunbiao.ybbusstopplate.base.ContentValue
import com.yunbiao.ybbusstopplate.message.ClearLayoutEvent
import com.yunbiao.ybbusstopplate.message.DownCompleteEvent
import com.yunbiao.ybbusstopplate.serialport.SerialPortConfig
import com.yunbiao.ybbusstopplate.ui.activity.FlavorType
import com.yunbiao.ybbusstopplate.ui.usbserver.UsbReceiver
import com.yunbiao.ybbusstopplate.ui.view.AutoPlayView
import com.yunbiao.ybbusstopplate.utils.FileTool
import com.yunbiao.ybbusstopplate.utils.SpTool
import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMessage
import com.yunbiao.ybbusstopplate.utils.eventbus.EventTAG
import com.yunbiao.ybbusstopplate.utils.eventbus.UsbEvent
import com.yunbiao.ybbusstopplate.utils.net.ResourceUpdate
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.util.concurrent.TimeUnit

class LeshanMainFragment : BaseFragment() {
    val TAG = "MainFragment"

    //设置fragment
    private var configFragment: ConfigFragment? = null

    //线路fragment
    private var leshanSiteFragment : LeshanSiteFragment? = null
    private var leshanLineInfoFragment : LeshanLineInfoFragment? = null

    companion object {
//        private const val showLine=1 //显示线路
//        private const val showAdvert=2 //显示广告
        //显示广告

        fun getInstance(): LeshanMainFragment {
            return LeshanMainFragment()
        }
    }

    override fun getViewId(): Int {
        return R.layout.fragment_leshan_main
    }

//    private val handler:Handler = object :Handler(Looper.getMainLooper()){
//        override fun dispatchMessage(msg: Message) {
//            super.dispatchMessage(msg)
//            removeMessages(msg.what)
//            when(msg.what){
//                showLine -> {
//                    showLineFragment()
//                }
//                showAdvert -> {
//                    val serialPortType = SpTool.getConfigSerialPortType();
//                    Log.d(TAG, "dispatchMessage: 检查广告设置：" + serialPortType + " --- " + SpTool.getConfigShowAdvert())
//                    if(serialPortType == SerialPortConfig.TYPE_HY && SpTool.getConfigShowAdvert()){
//                        val hyAdvertFragment = HYAdvertFragment();
//                        childFragmentManager.beginTransaction().add(R.id.fl_advert_show,hyAdvertFragment).show(hyAdvertFragment).commit()
//                    } else {
//                        playAdvert()//设置广告
//                    }
//                }
//            }
//        }
//    }

    private val compositeDisposable: CompositeDisposable = CompositeDisposable();
    private fun runDelay(timeMills: Long, consumer: Consumer<Long>) {
        val subscribe = Observable.timer(timeMills, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread()).subscribe(consumer)
        compositeDisposable.add(subscribe);
    }

    override fun initData() {
        EventBus.getDefault().register(this)

        if(leshanLineInfoFragment == null){
            leshanLineInfoFragment = LeshanLineInfoFragment.getInstance()
            requireActivity().supportFragmentManager.beginTransaction().replace(
                R.id.fl_line_info,
                leshanLineInfoFragment!!
            ).commit()
        }

        val serialPortType = SpTool.getConfigSerialPortType()
        if (serialPortType == -1) {//未设置厂家,显示配置dialog
            ll_noset_tip.visibility = View.VISIBLE
        } else {
            var showAdvert = SpTool.getConfigShowAdvert()
            if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                showAdvert = true
            }
            Log.e("showAdvert", "initData-----------------?$showAdvert")

            if (showAdvert) {
                fl_advert.visibility = View.VISIBLE
                var lineName = SpTool.get_line_name()
                if (!TextUtils.isEmpty(lineName)) {
                    tv_line_left.visibility = View.VISIBLE
                    tv_line_right.visibility = View.VISIBLE

                    if (lineName.contains("路")) {
                        lineName = lineName.replace("路", "")
                        lineName += "路"
                    }
                    tv_lineshow_name.text = lineName
                }
            }/* else {
                fl_advert.visibility = View.GONE
            }*/
            runDelay(300, Consumer {
                showLineFragment()
            })
//            handler.sendEmptyMessageDelayed(showLine, 1000)
        }

        registerUSBReceiver();
    }

    private lateinit var usbReceiver: UsbReceiver
    fun registerUSBReceiver() {
        usbReceiver = UsbReceiver(activity)

    }

    override fun onResume() {
        super.onResume()
        runDelay(300, Consumer {
            val serialPortType = SpTool.getConfigSerialPortType();
            Log.d(
                TAG,
                "dispatchMessage: 检查广告设置：" + serialPortType + " --- " + SpTool.getConfigShowAdvert()
            )
            if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN && SpTool.getConfigShowAdvert()){
                val hyAdvertFragment = HYAdvertFragment()
                childFragmentManager.beginTransaction().add(R.id.fl_advert_show, hyAdvertFragment)
                    .show(hyAdvertFragment).commit()
            } else if(SpTool.getConfigShowAdvert()){
                playAdvert()//设置广告
            }
        })
//        handler!!.sendEmptyMessageDelayed(showAdvert, 300)
    }

    override fun initListener() {
        btn_set.setOnClickListener {
            showSettingFragemnt()
        }
        v_set.setOnClickListener {
            showSet()
        }
    }

    override fun onDestroy() {
        BaseActivity.onBackKeyListener = null
        EventBus.getDefault().unregister(this)
        configFragment = null
        leshanSiteFragment = null
        leshanLineInfoFragment = null
//        handler.removeCallbacksAndMessages(this)
        compositeDisposable.dispose()
        usbReceiver.unregister()
        super.onDestroy()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(eventMessage: EventMessage) {
        when (eventMessage.msgTag) {
            //更新线路名
            EventTAG.EVENT_LINEINFO -> {
                if (tv_lineshow_name.visibility == View.GONE) {
                    return
                }
                val lineInfo = eventMessage.msgData as Array<String>
                var lineName = lineInfo[0]
                if (TextUtils.isEmpty(lineName)) {
                    tv_line_left.visibility = View.GONE
                    tv_line_right.visibility = View.GONE
                    tv_lineshow_name.text = getString(R.string.no_line_tip)
                } else {
                    tv_line_left.visibility = View.VISIBLE
                    tv_line_right.visibility = View.VISIBLE
                    if (lineName.contains("路")) {
                        lineName = lineName.replace("路", "")
                        lineName += "路"
                    }
                    tv_lineshow_name.text = lineName
                }
            }
            //设置页显示
            EventTAG.event_config_show -> {
                showSettingFragemnt()
            }

            //设置页隐藏
            EventTAG.event_config_dismiss -> {
                dismissSettingFragemnt()
            }

            //更新配置
            EventTAG.event_config_update -> {
                //线路页面
                showLineFragment()

                Log.d(TAG, "onEvent: 更新广告配置")
                if (SpTool.Companion.getConfigAdvertServerType()) {
                    playOnlineAdvert()
                } else {
                    playAdvert()//更新广告配置
                }
                //更新广告

            }
        }

    }

    private fun showSettingFragemnt() {
        BaseActivity.onBackKeyListener = object : BaseActivity.OnBackKeyListener {
            override fun onBack() {
                dismissSettingFragemnt()
            }
        }
        if (configFragment == null) {
            //初始化设置页
            configFragment = ConfigFragment.getInstance()
            requireActivity().supportFragmentManager.beginTransaction().replace(
                R.id.fl_config,
                configFragment!!
            ).commitAllowingStateLoss()
        }
        if (fl_config.visibility == View.VISIBLE) {
            return
        }
        fl_config.visibility = View.VISIBLE
    }

    private fun dismissSettingFragemnt() {
        BaseActivity.onBackKeyListener = null
        fl_config.visibility = View.INVISIBLE
        if (configFragment != null) {
            requireActivity().supportFragmentManager.beginTransaction().remove(configFragment!!)
                .commitAllowingStateLoss()
            configFragment = null
        }
    }

    private fun showLineFragment() {
        Log.e(TAG, "showLineFragment: 11111111111111 --- " + fl_config)
        fl_config.visibility = View.INVISIBLE
        ll_noset_tip.visibility = View.INVISIBLE

        if (leshanSiteFragment == null) {
            leshanSiteFragment = LeshanSiteFragment.getInstance()
            requireActivity().supportFragmentManager.beginTransaction().replace(
                R.id.fl_line_show,
                leshanSiteFragment!!
            ).commit()
        }
    }

    private fun isOuterEnable(): String? {
        val sdcardPath: String? = APP.getSmdt()?.smdtGetSDcardPath(activity);
        if (!TextUtils.isEmpty(sdcardPath) && !sdcardPath!!.contains("null")) {
            return sdcardPath
        }
        val usbPath0: String? = APP.getSmdt()?.smdtGetUSBPath(activity, 0);
        if (!TextUtils.isEmpty(usbPath0) && !usbPath0!!.contains("null")) {
            return usbPath0
        }

        val usbPath1: String? = APP.getSmdt()?.smdtGetUSBPath(activity, 1);
        if (!TextUtils.isEmpty(usbPath1) && !usbPath1!!.contains("null")) {
            return usbPath1
        }

        val usbPath2: String? = APP.getSmdt()?.smdtGetUSBPath(activity, 2);
        if (!TextUtils.isEmpty(usbPath2) && !usbPath2!!.contains("null")) {
            return usbPath2
        }

        val usbPath3: String? = APP.getSmdt()?.smdtGetUSBPath(activity, 3);
        if (!TextUtils.isEmpty(usbPath3) && !usbPath3!!.contains("null")) {
            return usbPath3
        }

        if (File(ContentValue.sdPath + File.separator + "video").exists()) {
            return ContentValue.sdPath
        }
        return ""
    }

    /**
     * 播放广告
     */
    private fun playAdvert() {
        if (SpTool.Companion.getConfigAdvertServerType()) {
            return
        }

        if (this.getResources()
                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
        ) {
            /*if (!SpTool.getConfigShowAdvert()) {//不显示广告区域
                fl_advert.visibility = View.GONE
                return
            }*/
            fl_advert.visibility = View.VISIBLE
            cleanAdvert()
//        val appPath = SpTool.getConfigAppPath()
//        val running = CommonUtils.getInstance().isAppRunning(context, ContentValue.advertAppPackageName)
            val appRunning = AppUtils.isAppRunning(ContentValue.advertAppPackageName)
            if (appRunning) {
                //显示客户广告app
                fl_advert.visibility = View.INVISIBLE
            } else {
                fl_advert.visibility = View.VISIBLE

                var resourcePath = ""
                resourcePath = isOuterEnable() + "/video"
                Log.e("outer", "isOuterEnable-------------->${isOuterEnable()}")
                if (TextUtils.isEmpty(isOuterEnable()) || isOuterEnable().equals("null") || isOuterEnable().equals(
                        "null?"
                    )
                ) {
                    resourcePath = SpTool.getConfigResourcePath()
                    val file = File(resourcePath)
                    if (file != null && !file.exists()) {
                        //创建文件夹
                        file.mkdirs()
                    }
                }

                val resourceList = FileTool.getResourceList(resourcePath)
                if (resourceList.size <= 0) {
                    return
                }
                val layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
                fl_advert_show.setBackgroundColor(Color.parseColor("#ffffff"))
                val autoPlayView = AutoPlayView(requireContext())
                fl_advert_show.addView(autoPlayView, layoutParams)
                autoPlayView.start(resourceList)
            }

        } else {
            fl_advert.visibility = View.VISIBLE
            cleanAdvert()

            fl_advert.visibility = View.VISIBLE
            var resourcePath = ""
            resourcePath = isOuterEnable() + "/video"
            Log.e("outer", "isOuterEnable-------------->${isOuterEnable()}")
            if (TextUtils.isEmpty(isOuterEnable()) || isOuterEnable().equals("null") || isOuterEnable().equals(
                    "null?"
                )
            ) {
                resourcePath = SpTool.getConfigResourcePath()
                val file = File(resourcePath)
                if (file != null && !file.exists()) {
                    //创建文件夹
                    file.mkdirs()
                }
            }

            val resourceList = FileTool.getResourceList(resourcePath)
            if (resourceList.size <= 0) {
                return
            }
            val layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            fl_advert_show.setBackgroundColor(Color.parseColor("#ffffff"))
            val autoPlayView = AutoPlayView(requireContext())
            fl_advert_show.addView(autoPlayView, layoutParams)
            autoPlayView.start(resourceList)
        }
    }

    fun playOnlineAdvert() {

        Log.e(
            TAG,
            "playOnlineAdvert: ------111------->" + LayoutCache.getLayoutCacheAsArray().length()
        )
        val resourceList = FileTool.getOnlineResourceList(LayoutCache.getLayoutCacheAsArray())

        Log.e(TAG, "playOnlineAdvert: -------222------>" + resourceList.size)

        for (ResouceBean in resourceList) {
            Log.e(TAG, "playOnlineAdvert: ------------------>" + ResouceBean.path)
        }
        if (resourceList.size <= 0) {
            return
        }
        cleanAdvert()
        fl_advert.visibility = View.VISIBLE
        val layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )
        fl_advert_show.setBackgroundColor(Color.parseColor("#ffffff"))
        val autoPlayView = AutoPlayView(requireContext())
        fl_advert_show.addView(autoPlayView, layoutParams)
        autoPlayView.start(resourceList)
    }

//    fun playOnlineAdvert2() {
//        if (this.getResources()
//                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
//        ) {
//            /*if (!SpTool.getConfigShowAdvert()) {//不显示广告区域
//                fl_advert.visibility = View.GONE
//                return
//            }*/
//            fl_advert.visibility = View.VISIBLE
//            cleanAdvert()
//            fl_advert.visibility = View.VISIBLE
//
//            val resourceList =
//                FileTool.getResourceList(ResourceUpdate.RESOURSE_PATH + ResourceUpdate.IMAGE_CACHE_PATH)
//            if (resourceList.size <= 0) {
//                return
//            }
//            val layoutParams = LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT,
//                LinearLayout.LayoutParams.MATCH_PARENT
//            )
//            fl_advert_show.setBackgroundColor(Color.parseColor("#ffffff"))
//            val autoPlayView = AutoPlayView(requireContext())
//            fl_advert_show.addView(autoPlayView, layoutParams)
//            autoPlayView.start(resourceList)
//
//
//        } else {
//            fl_advert.visibility = View.VISIBLE
//            cleanAdvert()
//            fl_advert.visibility = View.VISIBLE
//            val resourceList =
//                FileTool.getResourceList(ResourceUpdate.RESOURSE_PATH + ResourceUpdate.IMAGE_CACHE_PATH)
//            if (resourceList.size <= 0) {
//                return
//            }
//            val layoutParams = LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT,
//                LinearLayout.LayoutParams.MATCH_PARENT
//            )
//            fl_advert_show.setBackgroundColor(Color.parseColor("#ffffff"))
//            val autoPlayView = AutoPlayView(requireContext())
//            fl_advert_show.addView(autoPlayView, layoutParams)
//            autoPlayView.start(resourceList)
//        }
//    }

    open fun cleanAdvert() {
        val childCount = fl_advert_show.childCount
        if (childCount > 0) {
            fl_advert_show.removeAllViews()
            fl_advert_show.setBackgroundColor(Color.parseColor("#00000000"))
        }
    }

    //点击三次跳转设置页
    private var count = 3
    private var time = 0L
    private fun showSet() {
        if (count > 1) {
            val currentTimeMillis = System.currentTimeMillis()
            if (time == 0L) {
                time = currentTimeMillis
            }
            if (currentTimeMillis - time <= 2000) {//两秒内重复点击
                --count
                ToastUtils.showShort("再点击" + count + "次，进入设置页")
            } else {
                time = 0
                count = 3
                --count
                ToastUtils.showShort("再点击" + count + "次，进入设置页")
            }
        } else {
            count = 3
            time = 0
            showSettingFragemnt()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(usbEvent: UsbEvent) {
        Log.d(TAG, "onEvent: USB事件")
        playAdvert()//USB事件
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownCompleteEvent(downCompleteEvent: DownCompleteEvent) {
        Log.e(TAG, "onDownCompleteEvent:------------")
        Handler().postDelayed({ playOnlineAdvert() }, 500)

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onClearLayoutEvent(clearLayoutEvent: ClearLayoutEvent) {
        Log.e(TAG, "clearLayoutEvent:------------")
        cleanAdvert()
    }

}